#include "Map.h"
#include "Land.h"
#include "Pipe.h"
#include "Coin.h"

CMap::CMap()
{
}

void CMap::LoadMapFromFile(char* fileName)
{
	string data;
	ifstream fileStream(fileName);
	if (fileStream.is_open())
	{
		while (!fileStream.eof())
		{
			data += fileStream.get();
		}
	}
	vector<string> dataSplit = split(data, '\n');
	string temp = dataSplit[0];
	vector<string> temp_vector = split(temp, ' ');
	width =  atoi(temp_vector[0].c_str());
	height =  atoi(temp_vector[1].c_str());
	// Da co width va height
	// Cap phat mang
	mang = (int**)malloc(height * sizeof(int*));
	for (int i = 0; i < height; i++)
		mang[i] = (int*)malloc(width * sizeof(int));
	for (int i = 0; i < height; i++)
	{
		vector<string> temp_splip = split(dataSplit[i + 1], ' ');
		for (int j = 0; j < width; j++)
		{
			mang[i][j] = atoi(temp_splip[j].c_str());
		}
	}
	// Luu mang Ok
}

std::vector<std::string>& CMap::split(const std::string &s, char delim, std::vector<std::string> &elems)
{
	std::stringstream ss(s);
	std::string item;
	while(std::getline(ss, item, delim))
	{
		elems.push_back(item);
	}
	return elems;
}

std::vector<std::string> CMap::split(const std::string &s, char delim)
{
	std::vector<std::string> elems;
	return split(s, delim, elems);
}

vector<CObject*> CMap::GetObjects()
{
	vector<CObject*> ans;
	for (int i = 0; i < height; i++)
		for (int j = 0; j < width; j++)
		{
			if (mang[i][j] == 1)
			{
				CLand* wall = new CLand(D3DXVECTOR2(j * 50.0f , i * 50.0f + 300));
				wall->Init();
				ans.push_back(wall);
			} else if (mang[i][j] == 2)
			{
				CPipe* pipe = new CPipe(D3DXVECTOR2(j * 50.0f , i * 50.0f + 300));
				pipe->Init();
				ans.push_back(pipe);
			} else if (mang[i][j] == 3)
			{
				CCoin* coin = new CCoin(D3DXVECTOR2(j * 50.0f , i * 50.0f + 300));
				coin->Init();
				ans.push_back(coin);
			}
		}
		return ans;
}